package com.study.modules.mini.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.study.Util.Asserts;
import com.study.Util.IDUtil;
import com.study.annotation.bean.AppContext;
import com.study.common.constants.RedisCache;
import com.study.modules.mini.repository.model.WxUserDO;
import com.study.modules.mini.service.LoginService;
import com.study.modules.mini.service.WxUserService;
import com.study.modules.mini.wxjava.WxMultiService;
import com.study.modules.mini.wxjava.WxService;
import com.study.modules.saas.repository.model.UserDO;
import com.study.modules.saas.service.UserService;
import com.study.vo.WxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.Date;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-11-14 16:02
 * @Version 1.0
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    WxMultiService wxMultiService;
    @Autowired
    WxUserService wxUserService;
    @Value("${mini.appid}")
    private String appid;

    @Autowired
    RedisCache redisCache;
    @Override
    public AppContext login(String code) {
        Asserts.isEmpty(code, "code 为空");
        WxService wxService = wxMultiService.getWxService(appid);
        WxResponse wxResponse = wxService.wxLogin(code);
        Asserts.isNull(wxResponse, "登录失败");
        WxUserDO wxUserDO = wxUserService.getWxUserByOpenId(wxResponse.getOpenId());
        if(ObjectUtils.isNull(wxUserDO)){
            wxUserDO = new WxUserDO();
            wxUserDO.setUuid(IDUtil.randomUUID());
            wxUserDO.setOpenidId(wxResponse.getOpenId());
            wxUserDO.setUnionId(wxResponse.getUnionId());
            wxUserDO.setCreatedDate(new Date());
            wxUserDO.setLastLoginDate(new Date());
            wxUserService.createUser(wxUserDO);
        }
        wxUserService.updateUserLastLoginDate(wxUserDO.getUuid());
        String token = IDUtil.randomUUID();
        AppContext appContext = new AppContext();
        appContext.setUuid(wxUserDO.getUuid());
        appContext.setToken(token);
        redisCache.setAppContext(token, JSON.toJSONString(appContext));
        return appContext;
    }
}
